import cp from 'child_process'
import sudo from 'sudo-prompt'
const _cmd = 'WMIC PROCESS WHERE name="LeagueClientUx.exe" GET commandline'

function compact(array) {
  let resIndex = 0
  const result = []
  if (array == null) {
    return result
  }
  for (const value of array) {
    if (value) {
      result[resIndex++] = value
    }
  }
  return result
}
export const getAuth = (initFn) => {
  cp.exec(_cmd, function (error, stdout) {
    if (error) {
      initFn()
    }
    const _l = Buffer.from(stdout).length
    if (_l < 40) {
      const options = {
        name: 'Electron'
      }
      sudo.exec(_cmd, options, function (error, stdout) {
        if (error) {
          initFn()
        } else {
          const _bJson = Buffer.from(stdout).toJSON()
          _bJson.data = compact(_bJson.data)
          initFn(_bJson.data)
        }
      })
    } else {
      const _bJson = Buffer.from(stdout).toJSON()
      _bJson.data = compact(_bJson.data)
      if (error) throw error
      initFn(_bJson.data)
    }
  })
}
